package com.pentalog.ginet;

import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.pentalog.ginet.domain.Account;
import com.pentalog.ginet.domain.Employee;
import com.pentalog.util.HibernateUtil;
import com.pentalog.util.TimerGinet;

/**
 * Hello world!
 * 
 */
public class TestAccount {
	public static void main(String[] args) {
		TestAccount test = new TestAccount();
//		test.save();
		for (int i = 0; i < 5; i++) {
			test.getAll();
		}
		
	}
	public void getAll() {
		Session session = null;
		Transaction tx = null;
		Integer employeeID = null;
		TimerGinet time = null;
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();			
			tx = session.beginTransaction();
			time = new TimerGinet("TestAccount");
			String sql = "SELECT * FROM Account AS E order by E.name";
			SQLQuery query = session.createSQLQuery(sql);
			query.addEntity(Account.class);
//			query.setParameter("employee_id", 10);
			List results = query.list();
			for (int i = 0; i < results.size(); i++) {
				//System.out.println("First Name: " + ((Account)results.get(i)).getName());
			}
			tx.commit();
			time.done();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.clear();
			session.close();
		}

	}
	public void save() {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			tx = session.beginTransaction();
			Account account = new Account();
			account.setName("Joe");
			account.setAccountnumber("39084");
			account.setSetupdate(new Date());
			account.setBalance(4054.00);
			session.save(account);
			session.flush();
			tx.commit();
			Account account3 = (Account)session.get(Account.class, account.getId());
			Account account2 = (Account)session.load(Account.class, account.getId());
			
			System.out.println(account.getId() + " : " + account.getSetupdate());
			System.out.println(account2.getId() + " : " + account2.getSetupdate());
			System.out.println(account3.getId() + " : " + account3.getSetupdate());
			System.out.println("\n\n----------> OK");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("\n\n----------> false");
		} finally {
			// Actual contact insertion will happen at this step
			session.flush();
			session.close();

		}
	}
}
